import { ref } from 'vue';
import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', () => {
  // 登录状态
  const isLoggedIn = ref(false);
  
  // 用户信息
  const userInfo = ref<{
    nickname?: string;
    phone?: string;
    email?: string;
    avatar?: string;
    is_vip?: boolean;
    vip_expire_time?: string;
    token?: string;
  }>({});

  // 初始化时从 localStorage 恢复登录状态
  const initFromLocalStorage = () => {
    const savedState = localStorage.getItem('userState');
    if (savedState) {
      const { isLoggedIn: savedIsLoggedIn, userInfo: savedUserInfo } = JSON.parse(savedState);
      isLoggedIn.value = savedIsLoggedIn;
      userInfo.value = savedUserInfo;
    }
  };

  // 登录方法
  const login = (userData: {
    nickname?: string;
    phone?: string;
    email?: string;
    token: string;
    avatar?: string;
    is_vip?: boolean;
    vip_expire_time?: string;
  }) => {
    isLoggedIn.value = true;
    userInfo.value = userData;
    
    // 保存到 localStorage
    localStorage.setItem('userState', JSON.stringify({
      isLoggedIn: true,
      userInfo: userData
    }));
  };

  // 登出方法
  const logout = () => {
    isLoggedIn.value = false;
    userInfo.value = {};
    
    // 清除 localStorage
    localStorage.removeItem('userState');
  };

  // 初始化
  initFromLocalStorage();

  return {
    isLoggedIn,
    userInfo,
    login,
    logout
  };
});